<template>
  <div class="talent-recommend-container">
    <!-- 筛选区域 -->
    <div class="filter-container">
      <el-row :gutter="16">
        <el-col :span="4">
          <el-select
            v-model="educationFilter"
            placeholder="请选择学历（可多选）"
            clearable
            multiple
            @change="handleFilterChange"
            class="w-full"
          >
            <el-option label="大专" value="COLLEGE"></el-option>
            <el-option label="本科" value="UNDERGRADUATE"></el-option>
            <el-option label="硕士" value="MASTER"></el-option>
            <el-option label="博士" value="DOCTOR"></el-option>
            <el-option label="其他" value="OTHER"></el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select
            v-model="salaryFilter"
            placeholder="请选择薪资范围"
            clearable
            @change="handleFilterChange"
            class="w-full"
          >
            <el-option label="5k以下" value="0-5000"></el-option>
            <el-option label="5k-10k" value="5000-10000"></el-option>
            <el-option label="10k-20k" value="10000-20000"></el-option>
            <el-option label="20k-30k" value="20000-30000"></el-option>
            <el-option label="30k以上" value="30000+"></el-option>
          </el-select>
        </el-col>
      </el-row>
    </div>

    <div class="talent-card-list">
      <!-- 加载状态 -->
      <div
        v-if="loading"
        class="loading-state py-16 flex flex-col items-center justify-center"
      >
        <el-loading-spinner size="large"></el-loading-spinner>
        <p class="text-gray-500 mt-2">加载牛人数据中...</p>
      </div>

      <div
        v-else-if="filteredTalents.length === 0"
        class="empty-state py-16 flex flex-col items-center justify-center"
      >
        <el-empty description="暂无符合条件的牛人" image-size="120"></el-empty>
      </div>
      <div v-else>
        <div
          v-for="(talent, index) in filteredTalents"
          :key="talent.userId"
          class="talent-card"
          @mouseenter="handleCardHover(index, true)"
          @mouseleave="handleCardHover(index, false)"
          :style="{
            transform: cardHoverStates[index]
              ? 'translateY(-5px)'
              : 'translateY(0)',
          }"
        >
          <div class="main-content">
            <div class="talent-avatar">
              <img
                alt="头像"
                class="avatar-img"
                :src="talent.avatar || defaultAvatar"
              />
              <div
                class="online-indicator absolute -bottom-1 -right-1 bg-green-500 text-white text-xs rounded-full w-5 h-5 flex items-center justify-center shadow-sm"
              >
                在线
              </div>
            </div>

            <div class="talent-info">
              <div class="name-education">
                <h3 class="talent-name">{{ talent.name }}</h3>
                <span class="talent-education">{{
                  formatEducation(talent.education)
                }}</span>
              </div>

              <div class="meta-info">
                <span class="meta-item phone">
                  <i class="el-icon-phone-outline"></i>
                  {{ talent.phone }}
                </span>
                <span class="meta-item experience" v-if="talent.workExperience">
                  <i class="el-icon-time"></i>
                  {{ talent.workExperience }}
                </span>
              </div>

              <div class="job-intentions">
                <span class="intent-item position">
                  <i class="el-icon-briefcase"></i>
                  {{ talent.expectedPosition || "未填写" }}
                </span>
                <span class="intent-item industry">
                  <i class="el-icon-office-building"></i>
                  {{ talent.expectedIndustry || "未填写" }}
                </span>
                <span class="intent-item city" v-if="talent.expectedCity">
                  <i class="el-icon-location-outline"></i>
                  {{ talent.expectedCity }}
                </span>
              </div>
            </div>

            <div class="action-area">
              <div class="salary-tag">
                {{ formatSalary(talent.expectedSalary) }}
              </div>
              <el-button
                type="primary"
                @click="handleInterest(talent)"
                :disabled="isInterested(talent.userId)"
                class="interest-btn"
                :class="{
                  'bg-gray-100 text-gray-500 cursor-not-allowed': isInterested(
                    talent.userId
                  ),
                }"
              >
                <i class="el-icon-star-on"></i>
                感兴趣
              </el-button>
              <el-button
                @click="communicate(talent.userId, talent.name)"
                size="mini"
                ><i class="el-icon-chat-dot-round"></i>沟通</el-button
              >
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 15]"
        :page-size="pageSize"
        :total="totalTalents"
        layout="total, sizes, prev, pager, next, jumper"
        :disabled="loading"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import {
  getGoodSeekerList,
  interestedSeeker,
} from "@/api/recuriter/seekerrecommend";
import { formatTime } from "@/util/get-time";
export default {
  data() {
    return {
      educationFilter: [],
      salaryFilter: "0-5000",
      jobFilter: "",
      industryFilter: "",

      currentPage: 1,
      pageSize: 5,
      totalTalents: 0,

      allTalents: [],
      loading: false,
      interestedTalentIds: [],
      cardHoverStates: [],
      defaultAvatar:
        "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",
    };
  },

  computed: {
    filteredTalents() {
      return this.allTalents;
    },
  },

  created() {
    this.loadTalents();
  },

  methods: {
    async loadTalents() {
      this.loading = true;
      try {
        const { lowest, highest } = this.parseSalaryFilter();

        const params = {
          page: this.currentPage,
          size: this.pageSize,
          eduList: this.educationFilter,
          lowestSalaryMonth: lowest,
          highestSalaryMonth: highest,
          industry: this.industryFilter || "",
          positionName: this.jobFilter || "",
        };

        const response = await getGoodSeekerList(
          params.page,
          params.size,
          params.eduList,
          params.lowestSalaryMonth,
          params.highestSalaryMonth,
          params.industry,
          params.positionName
        );

        if (response.data.code === 201) {
          const { data } = response.data;
          this.allTalents = data.respList || [];
          this.totalTalents = data.total || 0;
          this.cardHoverStates = new Array(this.allTalents.length).fill(false);
        } else {
          this.$message.error(response.data.msg || "获取数据失败");
        }
      } catch (error) {
        console.error("获取牛人列表失败：", error);
        this.$message.error("网络错误，请重试");
      } finally {
        this.loading = false;
      }
    },

    parseSalaryFilter() {
      const salaryMap = {
        "0-5000": { lowest: 0, highest: 5000 },
        "5000-10000": { lowest: 5000, highest: 10000 },
        "10000-20000": { lowest: 10000, highest: 20000 },
        "20000-30000": { lowest: 20000, highest: 30000 },
        "30000+": { lowest: 30000, highest: 10000000000 },
      };
      return this.salaryFilter
        ? salaryMap[this.salaryFilter]
        : { lowest: null, highest: null };
    },

    handleFilterChange() {
      this.currentPage = 1;
      this.loadTalents();
    },

    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.loadTalents();
    },

    handleCurrentChange(page) {
      this.currentPage = page;
      this.loadTalents();
    },

    handleCardHover(index, isHover) {
      this.$set(this.cardHoverStates, index, isHover);
    },

    async handleInterest(talent) {
      if (!this.isInterested(talent.userId)) {
        try {
          const interestRes = await interestedSeeker(talent.userId);
          if (interestRes.data.code === 201) {
            this.$store.commit("recruiter/SET_TOKEN", interestRes.data.data);
            this.interestedTalentIds.push(talent.userId);
          }
        } catch (error) {
          this.$message.error("网络错误，请稍后尝试");
        }
      }
    },

    isInterested(userId) {
      return this.interestedTalentIds.includes(userId);
    },

    formatEducation(education) {
      const map = {
        COLLEGE: "大专",
        UNDERGRADUATE: "本科",
        MASTER: "硕士",
        DOCTOR: "博士",
        OTHER: "其他",
      };
      return map[education] || education;
    },

    formatSalary(salary) {
      if (!salary) return "薪资面议";
      return `${(salary / 1000).toFixed(0)}k/月`;
    },
    async communicate(userId, name) {
      try {
        const currentTime = formatTime();
        // 1. 发送消息
        await this.$store.dispatch("chat/sendChatMessage", {
          toUserId: userId,
          fromRole: "recruiter",
          content: this.$store.state.recruiter.Greeting,
          toRole: "seeker",
        });

        this.$confirm(
          `已向${name}发送沟通请求,如需修改打招呼内容，请在【账号与安全中心-设置招呼语】页面修改`,
          {
            confirmButtonText: "继续沟通",
            cancelButtonText: "留在此页",
            type: "warning",
          }
        )
          .then(() => {
            this.$router.push({
              name: "company-chat",
              params: { userId },
            });
          })
          .catch(() => {});
      } catch (error) {
        console.error("发送消息失败:", error);
        this.$message.error("消息发送失败，请稍后再试");
      }
    },
  },
};
</script>

<style scoped>
.talent-recommend-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.filter-container {
  margin-bottom: 16px;
  padding: 12px;
  border-radius: 6px;
}

.talent-card-list {
  margin-bottom: 16px;
}

/* 卡片样式 */
.talent-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.06);
  padding: 16px;
  margin-bottom: 14px;
  transition: all 0.3s ease;
  cursor: pointer;
  position: relative;
}

.talent-card:hover {
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.main-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

/* 头像样式 */
.talent-avatar {
  position: relative;
  flex-shrink: 0;
}

.avatar-img {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #f0f0f0;
  transition: transform 0.3s ease;
}

.talent-card:hover .avatar-img {
  transform: scale(1.05);
}

/* 信息区域 */
.talent-info {
  flex: 1;
  min-width: 0;
}

.name-education {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
}

.talent-name {
  font-size: 16px;
  font-weight: 600;
  margin: 0;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.talent-education {
  font-size: 12px;
  color: #666;
  background-color: #f5f7fa;
  padding: 1px 6px;
  border-radius: 4px;
  white-space: nowrap;
}

/* 元信息样式 */
.meta-info {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 8px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 12px;
  color: #666;
}

.meta-item i {
  color: #1890ff;
  font-size: 12px;
}

/* 求职意向样式 */
.job-intentions {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.intent-item {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 4px;
}

.intent-item.position {
  background-color: #f0f7ff;
  color: #1890ff;
}

.intent-item.industry {
  background-color: #f6ffed;
  color: #52c41a;
}

.intent-item.city {
  background-color: #fff7e6;
  color: #fa8c16;
}

.intent-item i {
  font-size: 12px;
}

/* 右侧操作区 */
.action-area {
  margin-left: auto;
  display: flex;
  align-items: center;
  gap: 15px;
  flex-shrink: 0;
}

.salary-tag {
  background-color: #fff1f0;
  color: #cf1322;
  padding: 4px 10px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
}

/* 按钮样式 */
.interest-btn {
  padding: 6px 16px;
  font-size: 12px;
  transition: all 0.2s ease;
}

.interest-btn:hover {
  transform: translateY(-2px);
}

/* 分页样式 */
.pagination-container {
  text-align: right;
  margin-top: 16px;
  padding-top: 8px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .main-content {
    flex-direction: column;
    align-items: flex-start;
  }

  .action-area {
    margin-left: 0;
    margin-top: 15px;
    width: 100%;
    justify-content: flex-end;
  }
}
</style>